﻿using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace SharePointStatus
{
    [Guid("c71d8db2-d6ce-4939-a0bd-09f60c3097f7")]
    public class SharePointStatus : System.Web.UI.WebControls.WebParts.WebPart
    {
        TextBox _myStatus = new TextBox();

        private string _listName;
        private string _siteUrl;
        private string _itemCount;
        private string _cachetimeout;
        private string _whoami = Environment.UserName;

        #region WebPart Configuration
        [WebBrowsable(true), Category("Configuration"), DefaultValue(""),
        Personalizable(true), FriendlyName("List Name"), Description("Name of the list to use for status updates.")]
        public string ListName
        {
            get { return _listName; }
            set { _listName = value; }
        }
        [WebBrowsable(true), Category("Configuration"), DefaultValue(""),
        Personalizable(true), FriendlyName("Site URL"), Description("Url of the site with the list to use.")]
        public string SiteURL
        {
            get { return _siteUrl; }
            set { _siteUrl = value; }
        }
        [WebBrowsable(true), Category("Configuration"), DefaultValue("10"),
        Personalizable(true), FriendlyName("Item Count"), Description("How many status items to show.")]
        public string ItemCount
        {
            get { return _itemCount; }
            set { _itemCount = value; }
        }
        [WebBrowsable(true), Category("Configuration"), DefaultValue("10"),
Personalizable(true), FriendlyName("Cache Timeout"), Description("How many minutes to wait before refreshing list items.")]
        public string CacheTimeout
        {
            get { return _cachetimeout; }
            set { _cachetimeout = value; }
        }
        #endregion
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            try
            {
                if ((ListName != null) && (SiteURL != null))
                {
                    RegisterScripts();
                    #region Add New Section
                    AddNew();
                    #endregion
                    #region Show Current Status Updates
                    // Use using to make sure resources are released properly   
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {

                            SPList oList = oWeb.Lists[ListName];  // The display name, ie. "Calendar" 
                            SPView oListView = oList.Views["All Items"];

                            Table _tbl = new Table();

                            SPListItemCollection collListItems;

                            lock (this)
                            {
                                //Check for Cache
                                if (HttpRuntime.Cache["SPStatusCache"] == null)
                                {
                                    //Not Cached
                                    collListItems = oList.GetItems(oListView);
                                    //SPListItemCollection collListItems = oList.GetItems(oListView);
                                    //Cache List Items Collection
                                    HttpRuntime.Cache.Add("SPStatusCache",
                                        collListItems,
                                        null,
                                        DateTime.MaxValue,
                                        TimeSpan.FromMinutes(Convert.ToDouble(_cachetimeout)),
                                        System.Web.Caching.CacheItemPriority.Default, null);
                                }
                                else
                                {
                                    collListItems = (SPListItemCollection)HttpRuntime.Cache["SPStatusCache"];
                                    //SPListItemCollection collListItems = HttpRuntime.Cache["SPStatusCache"];
                                }
                            }
                            

                            int iCount;

                            if (ItemCount != null)
                            {
                                iCount = Convert.ToInt32(ItemCount);
                            }
                            else
                            {
                                iCount = 10;
                            }

                            int eCount = 0;
                            foreach (SPListItem oItem in collListItems)
                            {
                                if ((eCount < iCount) && (eCount < collListItems.Count))
                                {
                                    if (oItem["Parent ID"] == null)
                                    {
                                        // Access each item in the list... 
                                        HtmlGenericControl lineBreak = new HtmlGenericControl("br");
                                        Label _beenLiked = new Label();
                                        Button _iLike = new Button();
                                        Label _iLike2 = new Label();
                                        Button _comment = new Button();
                                        Image _spacer = new Image();

                                        _spacer.ImageUrl = "/_layouts/images/blank.gif";
                                        _spacer.Width = 5;

                                        _beenLiked.Style.Add("font-size", "8pt");
                                        _beenLiked.Style.Add("color", "#999999");

                                        _iLike2.Style.Add("font-size", "8pt");
                                        _iLike2.Style.Add("color", "#999999");
                                        _iLike2.Text = "I Like this.  ";

                                        _iLike.Text = "Like";
                                        _iLike.Style.Add("Border", "0px");
                                        _iLike.Style.Add("Background", "transparent");
                                        _iLike.Style.Add("font-size", "8pt");
                                        _iLike.Style.Add("vertical-align", "bottom");
                                        _iLike.Style.Add("height", "10pt");
                                        _iLike.Style.Add("color", "#003399");
                                        _iLike.Style.Add("margin", "0px");
                                        _iLike.Style.Add("padding", "0px");
                                        _iLike.Style.Add("width", "auto");
                                        _iLike.Style.Add("cursor", "pointer");

                                        _iLike.ID = oItem["ID"].ToString();
                                        _iLike.Click += new EventHandler(_iLike_Click);


                                        _comment.Text = "Comment";
                                        _comment.Style.Add("Border", "0px");
                                        _comment.Style.Add("Background", "transparent");
                                        _comment.Style.Add("font-size", "8pt");
                                        _comment.Style.Add("vertical-align", "bottom");
                                        _comment.Style.Add("height", "10pt");
                                        _comment.Style.Add("color", "#003399");
                                        _comment.Style.Add("margin", "0px");
                                        _comment.Style.Add("padding", "0px");
                                        _comment.Style.Add("width", "auto");
                                        _comment.Style.Add("cursor", "pointer");

                                        _comment.ID = oItem["ID"].ToString(); ;


                                        //_comment.Attributes.Add("OnClick", "showLayer('"+_imID+"'); showLayer('"+_comID+"')");

                                        TableRow _rw = new TableRow();
                                        TableRow _rw3 = new TableRow();

                                        TableCell _ccell = new TableCell();
                                        Label _creater = new Label();
                                        TableCell _mcell = new TableCell();
                                        Label _suject = new Label();
                                        Label _datetime = new Label();
                                        _mcell.Style.Add("border-bottom", "1px solid #e5eaf1");

                                        //TableCell _sCell = new TableCell();

                                        _datetime.Style.Add("font-size", "8pt");
                                        _datetime.Style.Add("color", "#999999");

                                        Image _userImage = new Image();
                                        bool _IlikedIt = false;

                                        string _uid = oItem["Created By"].ToString().Substring(0, oItem["Created By"].ToString().IndexOf(";"));

                                        if (oItem["Liked"].ToString() != null && oItem["Liked"].ToString() != "0")
                                        {
                                            _IlikedIt = DoILike(oItem["Liked By"].ToString(), Convert.ToString(oWeb.CurrentUser.ID));
                                        }
                                        //try
                                        string _user = oItem["Created By"].ToString();
                                        int _index = _user.IndexOf(';');
                                        int id = Int32.Parse(_user.Substring(0, _index));
                                        SPUser _spuser = oWeb.SiteUsers.GetByID(id);


                                        _userImage.ImageUrl = GetUserImageURL(_spuser.LoginName);
                                        _userImage.Width = 50;

                                        _creater.Text = "<a href=\"/_layouts/userdisp.aspx?ID=" + _uid + "\">" + SPEncode.HtmlEncode(oItem["Created By"].ToString().Substring(oItem["Created By"].ToString().IndexOf("#") + 1, (oItem["Created By"].ToString().Length - oItem["Created By"].ToString().IndexOf("#") - 1))) + "</a> ";
                                        _suject.Text = StringMagic(oItem["Title"].ToString());
                                        _datetime.Text = "<br />" + SPEncode.HtmlEncode("Posted " + GetTimeSpace(Convert.ToDateTime(oItem["Created"].ToString())));

                                        _ccell.Controls.Add(_userImage);
                                        _mcell.VerticalAlign = VerticalAlign.Top;
                                        //_mcell.ColumnSpan = 2;
                                        _mcell.Controls.Add(_creater);
                                        _mcell.Controls.Add(_suject);
                                        //_mcell.Controls.Add(lineBreak);
                                        _mcell.Controls.Add(_datetime);
                                        //_mcell.Controls.Add(lineBreak);
                                         
                                        if (_IlikedIt) { 
                                            _mcell.Controls.Add(_iLike2); 
                                        }
                                        else { 
                                            _mcell.Controls.Add(_iLike); 
                                        }

                                        _mcell.Controls.Add(_spacer);
                                        //_mcell.Controls.Add(_comment);

                                        _rw.Cells.Add(_ccell);
                                        _rw.Cells.Add(_mcell);

                                        _tbl.Controls.Add(_rw);

                                        if ((oItem["Liked"].ToString() != null) && (oItem["Liked"].ToString() != "0"))
                                        {
                                            _beenLiked.Text = oItem["Liked"].ToString() + " people like this.   ";

                                            TableRow _likerw = new TableRow();
                                            TableCell _space = new TableCell();
                                            TableCell _likecell = new TableCell();
                                            Image _likeImage = new Image();

                                            _likeImage.ImageUrl = "/_layouts/images/ewr217s.gif";
                                            _likeImage.Style.Add("float","left");
                                            _likecell.Style.Add("background-color", "#eceff5");

                                            _likerw.Controls.Add(_space);
                                            _likecell.Controls.Add(_likeImage);
                                            _likecell.Controls.Add(_beenLiked);
                                            _likerw.Controls.Add(_likecell);

                                            _tbl.Controls.Add(_likerw);
                                        }

                                        if (GetChildren(oItem["ID"].ToString()))
                                        {
                                            GetChildrenComments(oItem["ID"].ToString(), _tbl);
                                        }

                                        //Add the Add Comment section here.
                                        TextBox _myComment = new TextBox();
                                        

                                        TableRow _row = new TableRow();
                                        TableCell _cell_ = new TableCell(); //Cell for blank
                                        TableCell _cell1 = new TableCell(); //Cell for Image
                                        Button _comButton = new Button();
                                        Image _meImage = new Image();


                                        _cell1.Style.Add("background-color", "#eceff5");
                                        _cell1.Style.Add("border-bottom", "1px solid #e5eaf1");

                                        _myComment.Width = Unit.Percentage(90);
                                        _myComment.ID = "Comment_" + oItem["ID"].ToString();
                                        _myComment.Attributes.Add("name", "Comment_" + oItem["ID"].ToString());
                                        _myComment.TextMode = TextBoxMode.MultiLine;
                                        _myComment.Rows = 1;
                                        
                                        _myComment.Attributes.Add("rows", "1");
                                        _myComment.MaxLength = 255;
                                        _myComment.Style.Add("overflow", "hidden");

                                        string _comID = "Commentbut_" + oItem["ID"].ToString();
                                        string _imID = "Image_" + oItem["ID"].ToString();

                                        //_comButton.ID = oItem["ID"].ToString();
                                        _comButton.Attributes.Add("ID", "Commentbut_" + oItem["ID"].ToString());
                                        _comButton.CommandArgument = oItem["ID"].ToString() + "; " + _myComment.Text;

                                        _comButton.Command += new CommandEventHandler(_comButton_Command);
                                        _comButton.Text = "Comment";

                                        _comButton.Style.Add("float", "right");
                                        _comButton.Style.Add("background-image", "url('_layouts/images/bluegradient.jpg')");
                                        _comButton.Style.Add("Border-style", "solid");
                                        _comButton.Style.Add("border-width", "1px");

                                        _meImage.Attributes.Add("ID", "Image_" + oItem["ID"].ToString());
                                        _meImage.ImageUrl = GetUserImageURL(_whoami);
                                        _meImage.Width = 32;

                                        _meImage.Style.Add("display", "none");
                                        _comButton.Style.Add("display", "none");

                                        _myComment.Attributes.Add("OnClick", "showLayer('" + _imID + "'); showLayer('" + _comID + "'); changeHeight(this);");
                                        _myComment.Attributes.Add("OnFocus", "");

                                        _cell1.Controls.Add(_meImage);
                                        _cell1.Controls.Add(_myComment);
                                        _cell1.Controls.Add(_comButton);

                                        //_row.Controls.Add(_sCell);
                                        _row.Controls.Add(_cell_);  //Blank cell
                                        _row.Controls.Add(_cell1);

                                        _tbl.Controls.Add(_row);
                                        //End Comment Box


                                    }
                                    //End of ParentID If
                                    eCount++;
                                }
                                //End of iCount If


                            }
                            this.Controls.Add(_tbl);
                        }
                    }


                }

                    #endregion
                else
                {
                    #region Not Configured
                    Label _message = new Label();
                    _message.Text = "Webpart is not configured.";
                    this.Controls.Add(_message);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                Label _error = new Label();
                _error.Text = ex.Message;
                this.Controls.Add(_error);
            }
        }
        void _comButton_Command(object sender, CommandEventArgs e)
        {
            Button _but = ((Button)sender);
            string[] vals = _but.CommandArgument.Split(';');

            string _optionID = "Comment_" + vals[0];
            TextBox _tb = (TextBox)this.FindControl(_optionID);
            string test = _tb.Text;

            if (vals[0] != null)
            {
                using (SPSite nSite = new SPSite(SiteURL))
                {
                    SPWeb nWeb = nSite.OpenWeb();
                    SPList nList = nWeb.Lists[ListName];
                    SPListItem nListItem = nList.Items.Add();
                    nListItem["Title"] = _tb.Text;
                    nListItem["Liked"] = "0";
                    nListItem["Parent ID"] = vals[0];
                    nListItem.Update();

                    Page.Response.Redirect(Page.Request.Url.ToString());

                }
            }
        }
        private bool GetChildren(string _id)
        {
            bool response = false;
            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists[ListName];  // The display name, ie. "Calendar" 
                    SPView oListView = oList.Views["All Items"];


                    Table _tbl = new Table();
                    SPListItemCollection collListItems = oList.GetItems(oListView);

                    foreach (SPListItem oItem in collListItems)
                    {
                        if (oItem["Parent ID"] != null)
                        {
                            string _item = oItem["Parent ID"].ToString();
                            int _index = _item.IndexOf(';');
                            int _parent = Int32.Parse(_item.Substring(0, _index));

                            if (_parent.ToString() == _id)
                            {
                                response = true;
                                break;
                            }
                        }
                    }
                }
            }

            return response;
        }
        private void GetChildrenComments(string _id, Table _table)
        {

            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists[ListName];  // The display name, ie. "Calendar" 
                    SPView oListView = oList.Views["All Items"];

                    Table _tbl = new Table();
                    SPListItemCollection collListItems = oList.GetItems(oListView);

                    foreach (SPListItem oItem in collListItems)
                    {
                        if (oItem["Parent ID"] != null)
                        {
                            string _item = oItem["Parent ID"].ToString();
                            int _pindex = _item.IndexOf(';');
                            int _parent = Int32.Parse(_item.Substring(0, _pindex));

                            if (_parent.ToString() == _id)
                            {
                                TableRow _ComRow = new TableRow();
                                TableCell _imageC = new TableCell();
                                //_imageC.Style.Add("background-color", "#eceff5");
                                _imageC.Width = 32;
                                _imageC.Style.Add("padding-left", "0px");
                                _imageC.Style.Add("padding-right", "0px");
                                //_imageC.Style.Add("border-bottom", "1px solid #e5eaf1");
                                TableCell _comment = new TableCell();
                                _comment.Style.Add("background-color", "#eceff5");
                                _comment.Style.Add("padding-left", "0px");
                                _comment.Style.Add("padding-right", "0px");
                                _comment.Style.Add("border-bottom", "1px solid #e5eaf1");
                                //TableCell _spacer = new TableCell();
                                Image _userImage = new Image();
                                Label _suject = new Label();
                                Label _datetime = new Label();
                                Label _creater = new Label();

                                string _user = oItem["Created By"].ToString();
                                int _index = _user.IndexOf(';');
                                int id = Int32.Parse(_user.Substring(0, _index));
                                SPUser _spuser = oWeb.SiteUsers.GetByID(id);
                                string _uid = oItem["Created By"].ToString().Substring(0, oItem["Created By"].ToString().IndexOf(";"));

                                _userImage.ImageUrl = GetUserImageURL(_spuser.LoginName);
                                _userImage.Width = 32;
                                _userImage.Style.Add("float","left");
                                _creater.Text = "<a href=\"/_layouts/userdisp.aspx?ID=" + _uid + "\">" + SPEncode.HtmlEncode(oItem["Created By"].ToString().Substring(oItem["Created By"].ToString().IndexOf("#") + 1, (oItem["Created By"].ToString().Length - oItem["Created By"].ToString().IndexOf("#") - 1))) + "</a> ";
                                _suject.Text = StringMagic(oItem["Title"].ToString());
                                _datetime.Text = "<br />" + SPEncode.HtmlEncode("Posted " + GetTimeSpace(Convert.ToDateTime(oItem["Created"].ToString())));

                                
                                //_imageC.Controls.Add(_userImage);
                                _comment.Controls.Add(_userImage);
                                _comment.Controls.Add(_creater);
                                _comment.Controls.Add(_suject);
                                _comment.Controls.Add(_datetime);

                                //_ComRow.Controls.Add(_spacer);
                                _ComRow.Controls.Add(_imageC);
                                _ComRow.Controls.Add(_comment);
                                
                                _table.Controls.Add(_ComRow);
                            }
                        }
                    }
                }
            }
        }
        private void AddNew()
        {

            Table _newtbl = new Table();
            _newtbl.CellPadding = 0;
            _newtbl.CellSpacing = 0;

            TableRow _newrw = new TableRow(); //Top Row for image and text box
            TableCell _newCell = new TableCell();// Left Cell for Image
            TableCell _newCell2 = new TableCell(); // Right cell for text box

            _newCell2.Width = Unit.Percentage(100);

            TableRow _rw2 = new TableRow();
            TableCell _newcell3 = new TableCell(); //place holder
            TableCell _newcell4 = new TableCell(); //for button right align

            //now make controls
            Image _meImage = new Image();

            _myStatus.Width = Unit.Percentage(95);
            _myStatus.Rows = 2;
            _myStatus.TextMode = TextBoxMode.MultiLine;
            _myStatus.MaxLength = 255;
            _myStatus.Style.Add("overflow", "hidden");
            Button _mySubmit = new Button();
            _mySubmit.Click += new System.EventHandler(_mySubmit_Click);
            _mySubmit.Text = "Share";
            _mySubmit.Style.Add("background-image", "url('_layouts/images/bluegradient.jpg')");
            _mySubmit.Style.Add("Border-style", "solid");
            _mySubmit.Style.Add("border-width", "1px");
            //end controls

            //string _whoami = Environment.UserName;

            _meImage.ImageUrl = GetUserImageURL(_whoami);
            _meImage.Width = 45;
            _newCell.Controls.Add(_meImage);
            _newCell2.VerticalAlign = VerticalAlign.Top;
            _newCell2.Controls.Add(_myStatus);
            _newcell4.HorizontalAlign = HorizontalAlign.Right;
            _newcell4.Controls.Add(_mySubmit);

            _newrw.Controls.Add(_newCell);
            _newrw.Controls.Add(_newCell2);

            _rw2.Controls.Add(_newcell3);
            _rw2.Controls.Add(_newcell4);

            _newtbl.Controls.Add(_newrw);
            _newtbl.Controls.Add(_rw2);

            this.Controls.Add(_newtbl);

        }
        private void RegisterScripts()
        {
            //Show Image and button for adding comments
            string SCRIPT = "<script language=\"JavaScript\">\n";
            SCRIPT += "function showLayer(layerName){\n";
            SCRIPT += " var targetElement = document.getElementById(layerName);\n";
            SCRIPT += "if (targetElement == null){return}\n else{";
            SCRIPT += " targetElement.style.display = 'inline'\n";
            SCRIPT += "}}\n";
            SCRIPT += "function changeHeight(element) {\n";
            SCRIPT += "var objs = document.getElementsByName(element.name);\n";
            SCRIPT += "if (objs.length > 0) {\n";
            SCRIPT += "var thefield = objs[0];\n";
            //SCRIPT += "alert('yes');";
            SCRIPT += "thefield.rows = 2;\n";
            SCRIPT += "}\n";                  
            SCRIPT += "}</script>\n";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "HideShowComment", SCRIPT);
            //Page.RegisterClientScriptBlock("HideShowComment", SCRIPT);

        }
        private void _iLike_Click(object sender, EventArgs e)
        {
            int _id = Convert.ToInt32(((Control)sender).ID);

            using (SPSite nSite = new SPSite(SiteURL))
            {
                SPWeb nWeb = nSite.OpenWeb();
                SPList nList = nWeb.Lists[ListName];
                SPUser _curUser = nWeb.CurrentUser;

                SPListItem nListItem = nList.GetItemById(_id);
                SPFieldUserValueCollection _userCollection = new SPFieldUserValueCollection();

                //Parse and look existing users in Liked By
                SPFieldUserValue usertoadd = ConvertLoginName(_curUser.ID.ToString());
                _userCollection.Add(usertoadd);

                nListItem["Liked"] = Convert.ToDecimal(nListItem["Liked"].ToString()) + 1;
                if (nListItem["Liked By"] != null)
                {
                    string[] _users = Regex.Split(nListItem["Liked By"].ToString(), ";#");
                    int _uid;
                    foreach (string _user in _users)
                    {
                        if (Int32.TryParse(_user, out _uid))
                        {
                            usertoadd = ConvertLoginName(Convert.ToString(_uid));
                            _userCollection.Add(usertoadd);
                        }
                    }
                }
                //nListItem["Liked By"] = nListItem["Liked By"].ToString() + ";" + _curUser.ID; 
                nListItem["Liked By"] = _userCollection;
                nListItem.Update();

                Page.Response.Redirect(Page.Request.Url.ToString());

            }
        }
        private bool isNumeric(string _str)
        {
            Regex _matchpattern = new Regex("[0-9]");
            return !_matchpattern.IsMatch(_str) && (_str != "");
        }
        public SPFieldUserValue ConvertLoginName(string _userId)
        {
            using (SPSite nSite = new SPSite(SiteURL))
            {
                SPWeb nWeb = nSite.OpenWeb();
                SPUser requireduser = nWeb.EnsureUser(ConvertToLogonName(Convert.ToInt32(_userId)));//.GetByID(Convert.ToInt32(_userId));
                SPFieldUserValue uservalue = new SPFieldUserValue(nWeb, requireduser.ID, requireduser.LoginName);
                return uservalue;
            }
        }
        private string ConvertToLogonName(int _ID)
        {
            using (SPSite nSite = new SPSite(SiteURL))
            {
                SPWeb nWeb = nSite.OpenWeb();
                SPUser oUser = nWeb.SiteUsers.GetByID(_ID);
                return oUser.LoginName.ToString();
            }
        }
        private string GetUserImageURL(string _logon)
        {
            string _result;
            using (SPSite pSite = new SPSite(SiteURL))
            {
                ServerContext _sitecontext = ServerContext.GetContext(pSite);
                UserProfileManager _user = new UserProfileManager(_sitecontext);
                try
                {
                    UserProfile _profile = _user.GetUserProfile(_logon);

                    _result = (string)_profile[PropertyConstants.PictureUrl].ToString();
                    //_result = _user.GetUserProfile(guid).ProfileManager.Properties.GetPropertyByName("PictureURL").ToString();
                }
                catch (Exception e)
                {
                    return "/_layouts/images/person.gif";
                }
            }
            return _result;
        }
        private string StringMagic(string _oldstring)
        {
            Regex urlregex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex surlregex = new Regex(@"(https:\/\/([\w.]+\/?)\S*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex emailregex = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            string _retval = "";

            try
            {
                if (_oldstring.Contains("http:"))
                {
                    _retval = urlregex.Replace(_oldstring, "<a href=\"$1\" target=\"_blank\">$1</a>");
                }
                else if (_oldstring.Contains("https:"))
                {
                    _retval = surlregex.Replace(_oldstring, "<a href=\"$1\" target=\"_blank\">$1</a>");
                }
                else if (_oldstring.Contains("@"))
                {
                    _retval = emailregex.Replace(_oldstring, "<a href=mailto:$1>$1</a>");
                }
                else
                {
                    return _oldstring;
                }

                return _retval;
            }
            catch (Exception ex)
            {
                return "Error converting string.  " + ex.Message;
            }
        }
        private string GetTimeSpace(DateTime dt1)
        {
            string _retval = "";
            TimeSpan ts = DateTime.Now - dt1;
            decimal _hours = Convert.ToDecimal(ts.TotalHours);
            if (_hours <= 24)
            {
                _retval = Math.Round(_hours, 0) + " hours ago.";
            }
            else
            {
                _retval = Math.Round((_hours / 24), 0) + " days ago.";
            }

            return _retval;
        }
        private bool DoILike(string _val, string _meval)
        {

            if ((_val.Contains("#" + _meval + ";")) || (_val.StartsWith(_meval + ";")))
            {
                return true;
            }
            else { return false; }
        }
        private void _mySubmit_Click(object sender, System.EventArgs e)
        {
            if ((_myStatus.Text.Length > 2) && (_myStatus.Text.Length < 256))
            {
                using (SPSite nSite = new SPSite(SiteURL))
                {
                    SPWeb nWeb = nSite.OpenWeb();
                    SPList nList = nWeb.Lists[ListName];

                    SPListItem nListItem = nList.Items.Add();
                    nListItem["Title"] = _myStatus.Text;
                    nListItem["Liked"] = "0";
                    nListItem.Update();

                    Page.Response.Redirect(Page.Request.Url.ToString());

                }
            }
        }
        private void SendAlert(SPUser _creator)
        {
            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    string _emailTo = _creator.Email.ToString();
                    string _Subject = "Someone commented on your status.";
                    string _body = "A comment has been added to your post.";
                    SPUtility.SendEmail(oWeb, false, false, _emailTo, _Subject, _body);
                }
            }
        }
    }
}